import { UserService } from './../user/user.service';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import * as md5 from 'md5';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
    constructor(private userService: UserService, private jwtService: JwtService) { }
    async login(userName, password) {
        const user = await this.userService.findByUsername(userName)

        if (!user) {
            throw new UnauthorizedException('账号不存在，请重新输入');
        }
        const md5Password = md5(password).toUpperCase();


        if (user.userPwd !== md5Password) {
            throw new UnauthorizedException('账号或密码错误，请重新尝试');
        }
        const payload = { username: user.userName, userid: user.id };

        const access_token = await this.jwtService.signAsync(payload, {
            expiresIn: '15m', // 15分钟
        })

        // ✅ 生成 Refresh Token（长期）
        const refresh_token = await this.jwtService.signAsync(payload, {
            expiresIn: '7d', // 7天
        });
        return {
            token: access_token,
            refresh_token,
        }
    }

    // 刷新access_token
    async refreshToken(refreshToken: string) {
        try {
            const decoded = await this.jwtService.verifyAsync(refreshToken);
            const payload = { username: decoded.username, userid: decoded.userid };

            const newAccessToken = await this.jwtService.signAsync(payload, {
                expiresIn: '15m',
            });

            return { token: newAccessToken };
        } catch (e) {
            throw new UnauthorizedException('refresh token 已失效，请重新登录');
        }
    }
}
